/**
 * 所属节点：盘点单列表
 * 创建人：zm
 * 创建时间：2024年8月26日
 * 最后修改人：zm
 */
cb.define(process.env.__DOMAINKEY__, function () {
  let GDGY01_dxq_checkstockList_VM_Extend = {
    doAction: function (name, viewModel) {
      if (this[name]) this[name](viewModel);
    },
    init: function (viewModel) {
      viewModel.on("customInit", function (data) {
        // console.log('[盘点单列表]');
        let tenantID = viewModel.getAppContext().tenant.tenantId;
        let userInfo = viewModel.getAppContext().user;
        const qianzhui = "/gdgy/pc/isv2";
        viewModel.on("afterMount", function () {
          viewModel.getCache("FilterViewModel").getParams().filterRows = 3;
          // 获取查询区模型
          const filtervm = viewModel.getCache("FilterViewModel");

          var shenheBtnModel = viewModel.get("button19jh"); //审核按钮
          var fupanBtnModel = viewModel.get("button28zk"); //复盘按钮

          var gridModel1 = viewModel.get("dxq_checkstock_2054777775847899242");
          gridModel1.setShowCheckbox(false); //主表去掉checkbox
          gridModel1._set_data("forbiddenDblClick", true); //主表去掉双击事件

          // console.log(gridModel1);

          //盘点单子单表--盘点单详情
          var gridModel2 = viewModel.get("dxq_checkstockAreaList");

          //根据单据状态判断部分操作按钮是否显示
          gridModel1.on("afterSetDataSource", () => {
            //获取列表所有数据
            const rows = gridModel1.getRows();
            //从缓存区获取按钮
            const actions = gridModel1.getCache("actions");
            // console.log(actions);
            if (!actions) return;
            const actionsStates = [];
            rows.forEach((data) => {
              const actionState = {};
              actions.forEach((action) => {
                actionState["button19jh"] = { visible: true }; // 审核
                actionState["button28zk"] = { visible: true }; // 申请复盘·
                actionState["button11ni"] = { visible: true }; // 查看盘点结果
                actionState["btnDelete"] = { visible: true }; // 删除
                if (data.IsFupan === "1" || data.IsFupan === 1) {
                  //1主单
                  if (data.iStatus === "0" || data.iStatus === 0) {
                    //只显示删除按钮
                    actionState["button19jh"] = { visible: false }; // 审核
                    actionState["button28zk"] = { visible: false }; // 申请复盘·
                    actionState["button11ni"] = { visible: false }; // 查看盘点结果
                  } else if (data.iStatus === "1" || data.iStatus === 1) {
                    //只显示查看盘点结果
                    actionState["btnDelete"] = { visible: false }; //删除
                    actionState["button19jh"] = { visible: false }; // 审核
                    actionState["button28zk"] = { visible: false }; // 申请复盘·
                  } else if (data.iStatus === "2" || data.iStatus === 2) {
                    //
                    actionState["btnDelete"] = { visible: false };
                    if (data.ShenheStatus === "0" || data.ShenheStatus === 0) {
                      //未审核
                      actionState["button19jh"] = { visible: true }; //显示审核
                      actionState["button28zk"] = { visible: true }; //显示申请复盘
                    } else {
                      //已审核
                      actionState["button19jh"] = { visible: false }; // 审核
                      actionState["button28zk"] = { visible: false }; // 申请复盘·
                    }
                  } else {
                    actionState["button19jh"] = { visible: false }; // 审核
                    actionState["button28zk"] = { visible: false }; // 申请复盘·
                  }
                } else {
                  //复核单
                  actionState["btnDelete"] = { visible: false };
                  if (data.iStatus === "0" || data.iStatus === 0) {
                    actionState["button19jh"] = { visible: false }; // 审核
                    actionState["button28zk"] = { visible: false }; // 申请复盘·
                    actionState["button11ni"] = { visible: false }; // 查看盘点结果
                  } else if (data.iStatus === "1" || data.iStatus === 1) {
                    actionState["btnDelete"] = { visible: false };
                    actionState["button19jh"] = { visible: false }; // 审核
                    actionState["button28zk"] = { visible: false }; // 申请复盘·
                  } else if (data.iStatus === "2" || data.iStatus === 2) {
                    if (data.ShenheStatus === "0" || data.ShenheStatus === 0) {
                      actionState["button19jh"] = { visible: true };
                      actionState["button28zk"] = { visible: true };
                    } else {
                      actionState["button19jh"] = { visible: false }; // 审核
                      actionState["button28zk"] = { visible: false }; // 申请复盘·
                    }
                  } else {
                    actionState["button19jh"] = { visible: false }; // 审核
                    actionState["button28zk"] = { visible: false }; // 申请复盘·
                  }
                }
              });
              actionsStates.push(actionState);
            });
            setTimeout(function () {
              gridModel1.setActionsState(actionsStates);
            }, 50);
          });

          // console.log('*****************');
          // console.log(gridModel2);

          gridModel2.setColumnState("iStatus", "formatter", function (rowInfo, rowData) {
            var iStatusValue = "";
            if (rowData.iStatus === "0") {
              iStatusValue = "<span title='未盘点'>未盘点</span>";
            } else if (rowData.iStatus === "1") {
              iStatusValue = "<span title='盘点中'>盘点中</span>";
            } else if (rowData.iStatus === "2") {
              iStatusValue = "<span title='盘点完成'>盘点完成</span>";
            } else if (rowData.iStatus === "4") {
              iStatusValue = "<span title='作废'>作废</span>";
            } else {
              iStatusValue = "";
            }
            return {
              override: true,
              html: iStatusValue,
            };
          });

          //删除前进行单据状态判断  只有未盘点可删除
          viewModel.on("beforeBatchdelete", function (params) {
            // console.log("beforeBatchdelete");
            // console.log(params);
            var deldata = JSON.parse(params.data.data);
            //console.log(deldata);
            if (deldata[0].iStatus === 0 || deldata[0].iStatus === "0") {
              // console.log(deldata[0].iStatus);
            } else {
              cb.utils.alert("只有盘点单状态为“未盘点”时才可以进行删除操作!");
              return false;
            }
          });

          //审核按钮点击事件
          shenheBtnModel.on("click", function (args) {
            // console.log("[shenheclick]");
            var currentRow = gridModel1.getRow(args.index);
            // console.log(currentRow);

            var timestr = new Date().format("yyyy-MM-dd hh:mm:ss");

            // cb.rest.invokeFunction(
            //   "GDGY01.pandian.pandianShenhe",
            //   {
            //     stockId: currentRow.id,
            //     Shenhetime: timestr,
            //   },
            //   function (err, res) {
            //     // console.log(err);
            //     // console.log(res);
            //     // throw new Error("err====="+err+"========res:==="+res);
            //     if (err === null && res !== null && typeof res.dataList != "undefined" && res.dataList.length == 0) {
            //       cb.utils.alert("操作成功!");
            //       cb.utils.loadingControl.end();
            //       viewModel.execute("refresh");
            //     } else if (res !== null && res !== undefined && err === null) {
            //       // 跳转处理页面判断
            //       let checkID = currentRow.id;
            //       var checkLocationNameNow = "";
            //       var productNameNow = "";
            //       var productUnitNow = "";
            //       var stockUnitNameNow = "";
            //       var checkStatusNow = "";
            //       //var iHandelMethodNow = "";
            //       var scanWayNow = "";
            //       var productskuNameNow = "";
            //       var pageNow = 1;
            //       var pageSizeNow = 10;

            //       var reqParams = {
            //         checkid: checkID,
            //         checklocationname: checkLocationNameNow,
            //         productname: productNameNow,
            //         productunit: productUnitNow,
            //         stockunitname: stockUnitNameNow,
            //         checkstatus: checkStatusNow,
            //         scanWay: scanWayNow,
            //         productskuname: productskuNameNow,
            //         page: pageNow,
            //         pagesize: pageSizeNow,
            //       };

            //       var ListResult = cb.rest.invokeFunction(
            //         "GDGY01.pandian.PdResultList",
            //         { reqParams: reqParams },
            //         function (err, res) {},
            //         viewModel,
            //         { async: false }
            //       );
            //       // console.log(ListResult);
            //       const res = JSON.parse(ListResult.result.strResponse);
            //       var blankInfo = false;
            //       if (res.dataList.length > 0) {
            //         var dataListContent = res.dataList;
            //         for (var i = 0; i < dataListContent.length; i++) {
            //           if (dataListContent[i].checkstatus == "0" || dataListContent[i].checkstatus == "2") {
            //             blankInfo = true;
            //             break;
            //           }
            //         }

            //         if (blankInfo) {
            //           cb.utils.confirm(
            //             "请处理盘盈或盘亏的数据",
            //             () => {
            //               //  success function 成功回调
            //               // 参数提交 查看返回参数是否正确，决定是否打印
            //               let data1 = {
            //                 billtype: "VoucherList", // 单据类型
            //                 billno: "dxq_checkdiff", // 单据号--跳转盘点分析列表
            //                 params: {
            //                   mode: "browse", // (编辑态、新增态、浏览态)
            //                   checkCode: currentRow.cCheckCode,
            //                 },
            //               };
            //               cb.loader.runCommandLine("bill", data1, viewModel);
            //             },
            //             () => {}
            //           );
            //         }
            //         cb.utils.alert("操作成功!");
            //         cb.utils.loadingControl.end();
            //       }
            //       viewModel.execute("refresh");
            //     } else {
            //       cb.utils.loadingControl.end();
            //       cb.utils.alert("系统出错!");
            //     }
            //   }
            // );

            /**
             * 张明迁移  盘点审核
             */
            //console.log("AAAAAA当前行", currentRow);
            const url_pandianshenhe =
              qianzhui +
              "/checkstock/checkShenhe?tenant_id=" +
              tenantID +
              "&userId=" +
              userInfo.userId +
              "&stockId=" +
              currentRow.id;
            const proxy_pandianshenhe = viewModel.setProxy({
              pandianshenhe: {
                url: url_pandianshenhe,
                method: "GET",
                options: {
                  mask: false,
                },
              },
            });
            proxy_pandianshenhe.pandianshenhe({}, function (err, res) {
              if (
                err === null &&
                res !== null &&
                typeof res.dataList != "undefined" &&
                (res.dataList == null || res.dataList.length == 0)
              ) {
                cb.utils.alert("操作成功!");
                cb.utils.loadingControl.end();
                viewModel.execute("refresh");
              } else if (res !== null && res !== undefined && err === null) {
                // 跳转处理页面判断
                let checkID = currentRow.id;
                var checkLocationNameNow = "";
                var productNameNow = "";
                var productUnitNow = "";
                var stockUnitNameNow = "";
                var checkStatusNow = "";
                //var iHandelMethodNow = "";
                var scanWayNow = "";
                var productskuNameNow = "";
                var pageNow = 1;
                var pageSizeNow = 10;

                var reqParams = {
                  checkid: checkID,
                  checklocationname: checkLocationNameNow,
                  productname: productNameNow,
                  productunit: productUnitNow,
                  stockunitname: stockUnitNameNow,
                  checkstatus: checkStatusNow,
                  scanWay: scanWayNow,
                  productskuname: productskuNameNow,
                  page: pageNow,
                  pagesize: pageSizeNow,
                };

                // var ListResult = cb.rest.invokeFunction(
                //   "GDGY01.pandian.PdResultList",
                //   { reqParams: reqParams },
                //   function (err, res) {},
                //   viewModel,
                //   { async: false }
                // );
                // // console.log(ListResult);
                /**
                 * 张明迁移
                 */
                let url_relist =
                  qianzhui +
                  "/checkstock/GetCheckresultList?tenant_id=" +
                  tenantID +
                  "&checkid=" +
                  reqParams.checkid +
                  "&checklocationname=" +
                  reqParams.checklocationname +
                  "&productname=" +
                  reqParams.productname +
                  "&productunit=" +
                  reqParams.productunit +
                  "&stockunitname=" +
                  reqParams.stockunitname +
                  "&checkstatus=" +
                  reqParams.checkstatus +
                  "&scanWay=" +
                  reqParams.scanWay +
                  "&productskuname=" +
                  reqParams.productskuname +
                  "&page=" +
                  reqParams.page +
                  "&pagesize=" +
                  reqParams.pagesize;
                const proxy_relist = viewModel.setProxy({
                  relist: {
                    url: url_relist,
                    method: "GET",
                    options: {
                      mask: false,
                    },
                  },
                });
                var ListResult = proxy_relist.relistSync({});
                const res = ListResult;
                var blankInfo = false;
                if (res.dataList.length > 0) {
                  var dataListContent = res.dataList;
                  for (var i = 0; i < dataListContent.length; i++) {
                    if (dataListContent[i].checkstatus == "0" || dataListContent[i].checkstatus == "2") {
                      blankInfo = true;
                      break;
                    }
                  }

                  if (blankInfo) {
                    cb.utils.confirm(
                      "请处理盘盈或盘亏的数据",
                      () => {
                        //  success function 成功回调
                        // 参数提交 查看返回参数是否正确，决定是否打印
                        let data1 = {
                          billtype: "VoucherList", // 单据类型
                          billno: "dxq_checkdiff", // 单据号--跳转盘点分析列表
                          params: {
                            mode: "browse", // (编辑态、新增态、浏览态)
                            checkCode: currentRow.cCheckCode,
                          },
                        };
                        cb.loader.runCommandLine("bill", data1, viewModel);
                      },
                      () => {}
                    );
                  }
                  cb.utils.alert("操作成功!");
                  cb.utils.loadingControl.end();
                }
                viewModel.execute("refresh");
              } else {
                cb.utils.loadingControl.end();
                cb.utils.alert("系统出错!");
              }
            });
          });

          //申请复盘按钮点击事件
          fupanBtnModel.on("click", function (args) {
            cb.utils.loadingControl.start();
            // console.log("[fupanBtnclick]");
            var currentRow = gridModel1.getRow(args.index);
            // console.log(currentRow);

            var timestr = new Date().format("yyyy-MM-dd hh:mm:ss");
            // cb.rest.invokeFunction(
            //   "GDGY01.pandian.CreatFupanStock",
            //   {
            //     billNum: "dxq_checkstockList", //单据编号--盘点单列表
            //     stockId: currentRow.id,
            //     Shenhetime: timestr,
            //   },
            //   function (err, res) {
            //     if (res !== null && res !== undefined && err === null) {
            //       cb.utils.loadingControl.end();
            //       cb.utils.alert("操作成功!");
            //       viewModel.execute("refresh");
            //     } else {
            //       cb.utils.loadingControl.end();
            //       cb.utils.alert("系统出错!");
            //     }
            //   }
            // );
            /**
             * 张明迁移
             */
            const url_fupan =
              qianzhui +
              "/checkstock/CreatFupanStock?userId=" +
              userInfo.userId +
              "&tenant_id=" +
              tenantID +
              "&stockId=" +
              currentRow.id;
            const proxy_fupan = viewModel.setProxy({
              fupan: {
                url: url_fupan,
                method: "GET",
              },
            });
            proxy_fupan.fupan({}, function (err, res) {
              if (res !== null && res !== undefined && err === null) {
                cb.utils.loadingControl.end();
                cb.utils.alert("操作成功!");
                viewModel.execute("refresh");
              } else {
                cb.utils.loadingControl.end();
                cb.utils.alert("系统出错!");
              }
            });

            // cb.rest.invokeFunction("cb56540954464d92a932c34cfe812036", {
            //     billNum: "76a30055List",
            //     stockId: currentRow.id,
            //     Shenhetime: timestr
            // },
            //     function (err, res) {
            //         if (res !== null && res !== undefined && err === null) {
            //             cb.utils.loadingControl.end();
            //             cb.utils.alert("操作成功!");
            //             viewModel.execute('refresh');
            //         } else {
            //             cb.utils.loadingControl.end();
            //             cb.utils.alert("系统出错!");
            //         }
            //     });
          });
        });
      });

      viewModel.get("button11ni") &&
        viewModel.get("button11ni").on("click", function (data) {
          // 查看盘点结果--单击
          // console.log("[查看盘点结果独立按钮]");
          var gridModel1 = viewModel.get("dxq_checkstock_2054777775847899242");
          //获取选中行的行号
          var line = gridModel1.getFocusedRowIndex();
          //获取选中行数据信息
          var checkTaskInfo = gridModel1.getRow(line);
          //传递给被打开页面的数据信息
          let data1 = {
            billtype: "VoucherList", // 单据类型
            billno: "dxq_checkresult", // 单据号
            params: {
              mode: "browse", // (编辑态edit、新增态add、浏览态browse)
              //传参
              checkTaskInfo: checkTaskInfo,
            },
          };
          // console.log("[modal]" + JSON.stringify(data1));
          // console.log(checkTaskInfo);
          //打开一个单据，并在当前页面显示
          cb.loader.runCommandLine("bill", data1, viewModel);
        });

      viewModel.get("button44ni") &&
        viewModel.get("button44ni").on("click", function (data) {
          // 新增盘点单--单击
          let data1 = {
            billtype: "Voucher", // 单据类型
            billno: "dxq_checkstock_create", // 单据号
            params: {
              mode: "edit",
              readOnly: false, // (编辑态edit、新增态add、浏览态browse)
            },
          };
          //打开一个单据，并在当前页面显示
          cb.loader.runCommandLine("bill", data1, viewModel);
        });

      viewModel.get("btnAdd") &&
        viewModel.get("btnAdd").on("click", function (data) {
          // 新增盘点单（全仓）--单击
          let data1 = {
            billtype: "Voucher", // 单据类型
            billno: "dxq_checkstock_createAll", // 单据号
            params: {
              mode: "add", // (编辑态edit、新增态add、浏览态browse)
            },
          };
          //打开一个单据，并在当前页面显示
          cb.loader.runCommandLine("bill", data1, viewModel);
        });

      viewModel.get("button28zk") &&
        viewModel.get("button28zk").on("click", function (data) {
          // 申请复盘--单击
        });
    },
  };
  try {
    module.exports = GDGY01_dxq_checkstockList_VM_Extend;
  } catch (error) {}
  return GDGY01_dxq_checkstockList_VM_Extend;
});
